package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.constant.MessageConstant;
import org.example.demo.entity.MeetingLog;
import org.example.demo.entity.User;
import org.example.demo.entity.UserStatus;
import org.example.demo.mapper.UserMapper;
import org.example.demo.service.MeetingLogService;
import org.example.demo.service.NotificationService;
import org.example.demo.service.UserMeetingService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.JWTUtils;
import org.example.demo.util.ReturnMap;
import org.example.demo.util.Upload;
import org.example.demo.util.encrypt.IEncryptService;
import org.example.demo.vo.UserStatusCntVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private NotificationService notificationService;

    @Resource
    private IEncryptService encryptService;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserMeetingService userMeetingService;

    @Autowired
    private MeetingLogService meetingLogService;


    /**
     * 登录 （接口测试通过）
     * @param user 用户
     * @return
     */
    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {
        //通过密码账号查询
        User selectUser = userService.checkLogin(user.getAccount(), user.getPwd());
        if (selectUser != null) {
            // 生成jwt token
            Map<String,Object> userMap = new HashMap<>();
            userMap.put("userId",selectUser.getId());
            String token = JWTUtils.genToken(userMap);
            Map retMap = new HashMap();
            retMap.put("token",token);
            retMap.put("user",selectUser);
            return AjaxResult.success(retMap);
        } else {
            return AjaxResult.error(MessageConstant.LOGIN_FAILED);
        }
    }

    //注册
    @PostMapping("register")
    public AjaxResult register(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> selectUser = userService.list(queryWrapper.lambda()
                .eq(User::getAccount, user.getAccount()).eq(User::getRole, user.getRole()));
        //查询是否有相同的账号
        if (!CollectionUtils.isEmpty(selectUser)) {
            return AjaxResult.error(MessageConstant.ALREADY_EXISTS);
        } else {
            user.setPoliticalStatus("群众");
            user.setCreateTime(LocalDateTime.now());
            userService.save(user);
            return AjaxResult.success();
        }
    }


    //用户查询列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody User user,  Integer pageNum, Integer pageSize) {
        Page<User> page1 = new Page<>();
        page1.setCurrent(pageNum);
        page1.setSize(pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //根据用户名、账号查询，注意是模糊查询
        Page<User> selectUser = userService.page(page1, queryWrapper.lambda()
                .like(null != user.getAccount() && !user.getAccount().isEmpty(), User::getAccount, user.getAccount())
                .like(null != user.getName() && !user.getName().isEmpty(), User::getName, user.getName())
                .eq(user.getRole()!=null&&!user.getRole().isEmpty(),User::getRole,user.getRole())
                .eq(user.getPoliticalStatus()!=null&&!user.getPoliticalStatus().isEmpty(),User::getPoliticalStatus,user.getPoliticalStatus())
                .eq(user.getDept() != null && !user.getDept().isEmpty(), User::getDept, user.getDept())
                .eq(user.getIdCard() != null, User::getIdCard, user.getIdCard())
                .orderByDesc(User::getCreateTime)
        );

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("page", selectUser);
        return AjaxResult.success(retMap);
    }


    //分页需要查询总条数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Integer count = userService.count(queryWrapper.lambda()
                .like(null != user.getName() && !user.getName().isEmpty(), User::getName, user.getName())
                .eq(user.getRole()!=null&&!user.getRole().isEmpty(),User::getRole,user.getRole())
                .like(null != user.getAccount() && !user.getAccount().isEmpty(), User::getAccount, user.getAccount())
                .eq(user.getDept() != null && !user.getDept().isEmpty(), User::getDept, user.getDept())
                .eq(user.getIdCard() != null, User::getIdCard, user.getIdCard())
                .eq(user.getPoliticalStatus()!=null&&!user.getPoliticalStatus().isEmpty(),User::getPoliticalStatus,user.getPoliticalStatus())
                .orderByDesc(User::getCreateTime));

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("count", count);
        return AjaxResult.success(retMap);
    }

    //修改用户信息
    @PostMapping("update")
    public AjaxResult update(@RequestBody User user) {

        // 先查看数据库原本的政治面貌
        User userOri = userService.getById(user.getId());
        // 如果两者政治面貌不一致，更新用户状态表表
        if (!Objects.equals(userOri.getPoliticalStatus(), user.getPoliticalStatus())) {
            userService.insertUserStatus(user);
        }

        if (userService.updateById(user)) {
            User user1=userService.getById(user.getId());
            Map<String,Object> map = new HashMap<>();
            map.put("user", user1);
            return AjaxResult.success(map);
        } else {
            return AjaxResult.error(MessageConstant.INTERNAL_SERVER_ERROR);
        }
    }


    //新增用户
    @PostMapping("insert")
    public AjaxResult insert(@RequestBody User user) {
        ReturnMap returnMap = new ReturnMap();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getId()!=null) {
            // 先查看数据库原本的政治面貌
            User userOri = userService.getById(user.getId());
            // 如果两者政治面貌不一致，更新用户状态表表
            if (!Objects.equals(userOri.getPoliticalStatus(), user.getPoliticalStatus())) {
                userService.insertUserStatus(user);
            }
            userService.updateById(user);
            return AjaxResult.success();
        }else{
            List<User> selectUser = userService.list(queryWrapper.lambda()
                    .eq(User::getAccount, user.getAccount()).eq(User::getRole, user.getRole()));
            if (!CollectionUtils.isEmpty(selectUser)) {
                    return AjaxResult.error();
            }
            user.setCreateTime(LocalDateTime.now());
            if (userService.save(user)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error();
            }
        }


    }


    //查询详情
    @PostMapping("selectById")
    public AjaxResult selectById(Integer id) {

        Map<String, Object> retMap = new HashMap<>();

        retMap.put("user", userService.getById(id));

        return AjaxResult.success(retMap);
    }


    //删除用户
    @DeleteMapping("deleteUser")
    public AjaxResult deleteById(@RequestParam("id") Integer id) {
        if (userService.removeById(id) ) {
            return AjaxResult.success();
        }

        return AjaxResult.error();
    }

    /**
     * 删除服务器上的文件 （接口测试通过）
     * @param path 服务器文件路径
     * @return
     */
    @DeleteMapping("deleteFile")
    public AjaxResult deleteFile(@RequestParam("filepath") String path) {
        String path_without_prefix = Upload.UPLOADED_FOLDER + path.replaceFirst("/file/","");
        File file = new File(path_without_prefix);
        if (file.delete()) {
            return AjaxResult.success();

        } else{
            return AjaxResult.error(MessageConstant.FILE_DELETE_ERROR);
        }
    }

    /**
     * 上传头像 （接口测试通过）
     * @param file 头像文件
     * @return
     */
    @RequestMapping("uploadImage")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        String shopImgDatai = null;
        try {
            shopImgDatai = Upload.uploadFile(file);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("imgUrl", shopImgDatai);

        return AjaxResult.success(map);
//        return new ResponseEntity(map, HttpStatus.OK);
    }

    /**
     * 更改密码 （接口测试通过）
     * @param pwd 新用户密码
     * @param request
     * @return
     */
    @GetMapping("changePwd")
    public AjaxResult changePwd(@RequestParam("pwd") String pwd,HttpServletRequest request) {
        // 拿到jwt
        String token = request.getHeader("Authorization");
        Integer id = (Integer) JWTUtils.parseToken(token).get("userId");
        User user = userService.getById(id);
        user.setPwd(pwd);
        userService.updateById(user);

        return AjaxResult.success();
//        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 获取用户信息 (接口测试通过)
     * @param id 用户id
     * @return
     */
    @GetMapping("userInfo")
    public AjaxResult userInfo(@RequestParam("id") Long id) {
        User user = userService.getById(id);

        Map<String,Object> map = new HashMap<>();
        map.put("user", user);

        return AjaxResult.success(map);
//        return new ResponseEntity(map, HttpStatus.OK);
    }


    /**
     * 通过用户id获取用户状态
     * @param request
     * @return
     */
    @GetMapping("/status")
    public AjaxResult listStatus(HttpServletRequest request) {

        // 获取用户Id
        String token = request.getHeader("Authorization");
        Integer id = (Integer) JWTUtils.parseToken(token).get("userId");

        // 根据id获取用户状态
        List<UserStatus> userStatusList = userService.listStatus(id);

        // 封装
        Map<String, Object> map = new HashMap<>();
        map.put("userStatusList", userStatusList);

        return AjaxResult.success(map);
//        return new ResponseEntity(map, HttpStatus.OK);
    }

    /**
     * 检查用户token是否有效 (接口测试通过)
     * @return
     */
    @GetMapping("/validateToken")
    public AjaxResult validateToken(@RequestParam("token") String token) {
        if (token == null || token.isEmpty() || !JWTUtils.checkToken(token)) {
            // token无效的情况
            return AjaxResult.error(HttpStatus.UNAUTHORIZED.value(),"用户凭证过期或失效");
        }
        return AjaxResult.success();
    }

    /**
     * 获取用户状态分类数量
     * @param request
     * @return
     */
    @GetMapping("/status/cnt")
    public AjaxResult getUserStatusCnt(HttpServletRequest request) {


        List<UserStatusCntVO> userStatusCntList = userService.getUserStatusCnt();

        Map<String, Object> map = new HashMap<>();
        map.put("userStatusCnt", userStatusCntList);
        return AjaxResult.success(map);
    }


    /**
     * 获取所有用户
     * @return users
     */
    @GetMapping("/list")
    public AjaxResult getUserList() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userStatusCntList = userService.list(queryWrapper.lambda().eq(User::getRole,"用户"));
        Map<String, Object> map = new HashMap<>();
        map.put("users", userStatusCntList);
        return AjaxResult.success(map);
    }

    /**
     * 获取用户所参加的会议信息
     * @param request
     * @return
     */
    @GetMapping("/selectMeeingLogs")
    public AjaxResult selectMeetings(HttpServletRequest request) {
        // 获取用户Id
        String token = request.getHeader("Authorization");
        Long id = (Long) JWTUtils.parseToken(token).get("userId");

        // 得到会议id
        List<MeetingLog> meetingLogs = new ArrayList<>();
        List<Long> meetingIds = userMeetingService.getMeetingIdsByUserId(id);

        // 得到会议信息
        for (Long meetingId : meetingIds) {
            meetingLogs.add(meetingLogService.getById(meetingId));
        }

        // 封装
        Map<String, Object> map = new HashMap<>();
        map.put("meetingLogs", meetingLogs);
        return AjaxResult.success(map);
    }


    /**
     * 获取相同和本id相同系的人
     * @param id
     * @return
     */
    @GetMapping("/selectSameDeptPeople/{id}")
    public AjaxResult selectSameDeptPeople(@PathVariable Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userService.getById(id);

        wrapper
                .eq("dept", user.getDept())
                .notLike("role", "党支部");

        List<User> users = userMapper.selectList(wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("sameDeptPeople", users);

        return AjaxResult.success(map);
    }

    /**
     * 获取当前用户id属于哪个支部
     * @param id 用户id
     * @return 党支部用户信息
     */
    @GetMapping("/getDeptId/{id}")
    public AjaxResult getDeptId(@PathVariable Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userService.getById(id);

        wrapper
                .eq("dept", user.getDept())
                .eq("role", "党支部");

        User dept_user = userMapper.selectOne(wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("deptUser", dept_user);

        return AjaxResult.success(map);
    }

}
